import 'dart:isolate';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:image_preview/image/model/_data.dart';

import '../../model/DataProvider.dart';
import 'ImageItem.dart';
import 'ImagePreviewModel.dart';

class ImagePreviewViewModel extends ChangeNotifier {
  late final ImagePreviewModel model = ImagePreviewModel();
  late PageController _pageController;
  final ReceivePort _port = ReceivePort();

  // 初始化参数
  ImageData imageData = ImageData([], "", "",0);

  // 图片列表
  List<ImageItem> _images = [];

  List<ImageItem> get images => _images;

  ImagePreviewViewModel() {
    IsolateNameServer.registerPortWithName(
        _port.sendPort, 'downloader_send_port');
    _port.listen((dynamic data) {
      String id = data[0];
      DownloadTaskStatus status = DownloadTaskStatus.fromInt(data[1]);
      int progress = data[2];
      bool notify = model.updateDownloadProgress(id, status, progress);
      if (notify) {
        notifyListeners();
      }
    });
  }

  // 初始化数据
  Future<void> initData() async {
    if (kDebugMode) {
      print("ImagePreview: _onInitialImage,  初始化数据");
    }
    imageData = ImageData(
      DataProvider.params,
      "",
      "",
      1,
    );
    _pageController = PageController(initialPage: imageData.index);
    _images = DataProvider.params.map((url) => ImageItem(url: url)).toList();
    notifyListeners();
  }

  Future<void> downloadImage(ImageItem image) async {
    if (await model.isDownloaded(image, imageData.bookId)) {
      notifyListeners();
      return;
    }
    image.state = ImageState.downloading;
    notifyListeners();
    try {
      await model.downloadImage(image);
    } catch (e) {
      if (kDebugMode) {
        print("ImagePreview: downloadImage,  下载图片失败: $e");
      }
      image.state = ImageState.error;
      notifyListeners();
    }
  }

  get pageController => _pageController;
}
